<template>
	<view class="registerbg">

		<view class="bgfff" style="width: 100%; height: 90rpx;line-height: 90rpx;">
			<u-tabs :list="tabList" @click="tabsClick" :scrollable='false' :current='currentTab' lineWidth="40"
				lineColor="#2979ff"></u-tabs>
		</view>

		<view class="pad20 form-center">
			<u--form labelPosition="left" ref="uForm">
				<view class="formView" v-if="currentTab===0">
					<u-form-item label="识别票据" prop="producedBillImage" ref="producedBillImage" label-width="80px"
						required>
						<view class="imgView">
							<image v-if="!producedBillImage" class="fileimg1" src="../../static/index/add.png"
								@click="chooseImage"></image>
							<image v-else class="fileimg1" :src="producedBillImage.path"></image>
							<view v-if="producedBillImage" class="del" @click="delimg">
								<u-icon name="close-circle-fill" size='20' color='red'></u-icon>
							</view>
						</view>
					</u-form-item>
				</view>

				<view class="formView">
					<u-form-item label="出矿吨数" prop="producedTons" ref="producedTons" label-width="80px" required>
						<u--input :disabled="currentTab===0?true:false" disabledColor='#fff' type='digit'
							v-model="producedTons" border="none" :placeholder="currentTab===0 ? '请识别票据' : '请输入'">
						</u--input>
					</u-form-item>
				</view>

				<view class="formView">
					<u-form-item label="出矿时间" prop="producedTime" ref="producedTime" label-width="80px" required>
						<view :class="producedTime?'color333':'colorc4'" @click="clickShowTime">
							{{producedTime||(currentTab===0 ? '请识别票据' : '请选择')}}
						</view>
					</u-form-item>
				</view>

				<view class="formView" v-if="currentTab===1">
					<u-form-item label="出矿票据" prop="producedBillImage" ref="producedBillImage" label-width="80px"
						required>
						<!-- <u-upload :fileList="fileList" name="1"  :maxCount="1"></u-upload> -->
						<view class="imgView">
							<image v-if="!producedBillImage" class="fileimg1" src="../../static/index/add.png"
								@click="chooseFile"></image>
							<image v-else class="fileimg1" :src="producedBillImage.path"></image>
							<view v-if="producedBillImage" class="del" @click="delimg">
								<u-icon name="close-circle-fill" size='20' color='red'></u-icon>
							</view>
						</view>
					</u-form-item>
				</view>
				<view class="formView">
					<u-form-item label="煤运客户" prop="clientld" ref="clientld" label-width="80px" required>
						<view :class="clientName?'color333':'colorc4'" @click="clickpicker">
							{{clientName||'请选择'}}
						</view>
					</u-form-item>
				</view>
				<view class="formView">
					<u-form-item label="煤运口令" prop="checkCode" ref="checkCode" label-width="80px" required>
						<u--input disabledColor="#fff" v-model="checkCode" border="none" placeholder="请输入"></u--input>
					</u-form-item>
				</view>
			</u--form>
			<view v-if="Loading" class="modifybts bg999 colorfff bdRadius20 marAuto marT32">提交中...</view>
			<view v-else class="modifybts bgMain colorfff bdRadius20 marAuto marT32" @tap="$u.throttle(submit0, 1000)">
				提交
			</view>
			<!-- 
			<view class="modifybts bgGreen colorfff bdRadius20 marAuto marT32" @tap="ditu()">
				地图
			</view> -->
		</view>
		<u-picker :show="pickerShow" :columns="columns" @confirm='pickerConfirm' @cancel='pickerCancel'
			keyName="clientName"></u-picker>

		<u-datetime-picker :show="timeShow" v-model="value1" mode="datetime" @confirm="onTimeConfirm"
			@cancel="onTimeCancel" />
	</view>
</template>

<script>
	import {
		toBase64 as convert
	} from "@/common/base64.js"
	import commonApi from '@/api/common.js'
	export default {
		data() {
			return {
				inputStyle: {
					padding: '15rpx 20rpx',
				},
				producedTons: '',
				producedBillImage: null,
				checkCode: '',
				fileList: [],
				textList: [],
				Loading: false,
				clientName: '',
				clientId: '',
				pickerShow: false,
				columns: [
					[]
				],

				tabList: [{
					name: '识别登记',
					value: 0,
				}, {
					name: '录入登记',
					value: 1,
				}, ],

				currentTab: 0,


				producedTime: "", //出矿时间
				timeShow: false,
				value1: Number(new Date()),
				isdisabled: false, //是否从运输情况中跳转过来
				data: {}
			}
		},
		onLoad(e) {
			if (e.data) {
				this.data = JSON.parse(e.data)
				this.clientId = this.data.clientId;
				this.checkCode = this.data.checkCode;
				this.isdisabled = true;
			}
			this.clientList()
		},
		methods: {
			tabsClick(e) {
				this.producedTime = '';
				this.producedTons = '';
				this.producedBillImage = null;
				this.currentTab = e.value;
			},
			clickShowTime() {
				if (this.currentTab === 0) return
				this.timeShow = true;
			},

			chooseFile() {
				let that = this;
				wx.chooseImage({
					count: 1,
					success(res) {
						that.producedBillImage = res.tempFiles[0];
					}
				})
			},

			// 选择本地图片
			chooseImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						uni.showLoading({
							title: '正在识别中...'
						})
						// 下面将图片本地路径转base64
						this.producedBillImage = res.tempFiles[0]
						convert(res.tempFilePaths[0]).then((res) => {
							this.getAccessToken(res)
						})
					}
				})
			},
			// 获取AccessToken
			getAccessToken(path) {
				uni.request({
					url: 'https://aip.baidubce.com/oauth/2.0/token',
					data: {
						grant_type: 'client_credentials',
						client_id: "m9Iy3VricHzjrZ9a9qa2Kvzk", //高精度含位置
						client_secret: "e17GOEo4Qgs73INy0eghYnTv5tbUw3Lr",
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						this.uploadImage(path, res.data.access_token)
					}
				})
			},
			// 通用文字识别（高精度版）
			uploadImage(path, token) {
				uni.request({
					url: "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate", //高精度含位置
					data: {
						image: path,
						access_token: token
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						uni.hideLoading()
						let showEr = res.data.words_result
						//高精度含位置接口处理出矿识别
						for (let i = 0; i < showEr.length; i++) {
							if (showEr[i].words.includes("净重")) {
								//出矿吨数
								this.producedTons = showEr[i + 1].words
								console.info(showEr[i].words, this.producedTons)
							} else if (showEr[i].words.includes("重车时间")) {
								//出矿时间
								this.producedTime = showEr[i + 1].words + " " + showEr[i + 2].words
								console.info(showEr[i].words, this.producedTime)
							} else {

							}
						}
						if (this.numStr == "") {
							uni.showToast({
								title: "识别失败，请重试",
								icon: "fail",
								duration: 2000,
								mask: true
							})
						}
					},
					fail() {
						uni.hideLoading()
					}
				})
			},

			//煤运用户列表
			clientList() {
				commonApi.clientList().then((res) => {
					if (res.status == 200) {
						let list = res.data;
						if (this.clientId) {
							list.forEach(e => {
								if (this.clientId == e.id) {
									this.clientName = e.clientName;
								}
							})
						}
						this.columns[0] = list
					}
				});
			},
			clickpicker() {
				if (!this.isdisabled) {
					this.pickerShow = true;
				}
			},
			pickerCancel() {
				this.clientName = '';
				this.clientId = '';
				this.pickerShow = false;
			},
			pickerConfirm(e) {
				// console.log(e.value)
				this.clientName = e.value[0].clientName;
				this.clientId = e.value[0].id;
				this.pickerShow = false;
			},

			delimg() {
				this.producedBillImage = null;
				if (this.currentTab === 0) {
					this.producedTime = '';
					this.producedTons = ''
				}
			},


			submit0() {
				let that = this;
				if (!that.producedTons) {
					that.showMsg('请输入出矿吨数')
					return
				}
				if (!that.isNonNegativeFloat(that.producedTons)) {
					that.showMsg('出矿吨数格式不正确')
					return
				}
				if (!that.producedBillImage) {
					that.showMsg('请上传出矿票据')
					return
				}
				if (!that.checkCode) {
					that.showMsg('请输入煤运口令')
					return
				}
				this.requestLocationPermission()

			},

			//位置权限申请
			requestLocationPermission() {
				console.log('位置权限申请~~~')
				let that = this
				wx.authorize({
					scope: 'scope.userLocation',
					success() {
						that.orderSubmit()
						that.$store.commit('setLocationWatch', true);
					},
					fail() {
						wx.showModal({
							title: '提示',
							content: '请授权位置权限，否则无法使用定位功能',
							confirmText: '去设置',
							success(res) {
								if (res.confirm) {
									wx.openSetting({
										success(settingRes) {
											if (settingRes.authSetting['scope.userLocation']) {
												that.$store.commit('setLocationWatch', true);
												that.orderSubmit()
											} else {
												uni.showToast({
													title: '未开启位置权限',
													icon: 'none'
												});
											}
										}
									});
								} else {
									uni.showToast({
										title: '未开启位置权限',
										icon: 'none'
									});
								}
							}
						});
					}
				});
			},


			orderSubmit() {
				let that = this;
				uni.showLoading({
					title: '加载中',
				})
				that.Loading = true;
				wx.uploadFile({
					url: that.baseUrl + '/client/freightSettlement/submit0',
					filePath: that.producedBillImage.path,
					name: 'producedBillImage',
					formData: {
						producedTons: that.producedTons,
						producedTime: that.producedTime,
						checkCode: that.checkCode,
						clientId: that.clientId
					},
					header: {
						'Authorization': uni.getStorageSync('token') || '',
					},
					success(uploadFileRes) {
						// uni.hideLoading()
						let rs = JSON.parse(uploadFileRes.data)
						if (rs.status == 200) {
							that.showMsg('操作成功')
							that.Loading = false;
							setTimeout(e => {
								// that.goOpen('/pages/tabbar/index')
								that.goToPage(`/pages/index/position?data=${JSON.stringify(that.data)}`)
							}, 10)
						} else {
							that.showMsg(rs.message)
							that.Loading = false;
						}
					},
					fail(ra) {
						uni.hideLoading()
						that.Loading = false;
					}
				})
			},

			ditu() {
				this.goToPage(`/pages/index/position?data=${JSON.stringify(this.data)}`)
			},
			onTimeConfirm(e) {
				// e为时间戳，格式化为字符串
				const date = new Date(e.value);
				const Y = date.getFullYear();
				const M = (date.getMonth() + 1).toString().padStart(2, '0');
				const D = date.getDate().toString().padStart(2, '0');
				const h = date.getHours().toString().padStart(2, '0');
				const m = date.getMinutes().toString().padStart(2, '0');
				const s = date.getSeconds().toString().padStart(2, '0');
				this.producedTime = `${Y}-${M}-${D} ${h}:${m}:${s}`;
				this.timeShow = false;
			},
			onTimeCancel() {
				this.timeShow = false;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.registerbg {
		width: 100%;
		min-height: calc(100vh - var(--window-bottom));
		display: flex;
		flex-direction: column;
		align-items: center;

		.tabs-center {
			width: 100%;
			display: flex;
			justify-content: center;
			margin-top: 40rpx;
			margin-bottom: 20rpx;
		}

		.gyview {
			background-size: 100% 100%;
			background-repeat: no-repeat;
			padding: 30rpx 36rpx;
			border-radius: 20rpx;
		}

		.form-center {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
		}

		.formView {
			width: 600rpx;
			max-width: 90vw;
			padding: 20rpx 36rpx;
			background: #fff;
			margin-top: 20rpx;
			border-radius: 20rpx;
			box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.06);

			.topline {
				padding-top: 30rpx;
				border-top: 1rpx solid #E3E4E5;
			}

			.imgView {
				position: relative;
				height: 138rpx;
				width: 138rpx;

				.fileimg1 {
					position: absolute;
					top: 0;
					left: 0;
					width: 138rpx;
					height: 138rpx;
				}

				.del {
					position: absolute;
					right: -10rpx;
					top: -10rpx;
				}
			}
		}

		.modifybts {
			text-align: center;
			height: 90rpx;
			line-height: 90rpx;
			width: 600rpx;
			max-width: 90vw;
			margin-top: 32rpx;
		}


		.icon-size {
			width: 40rpx;
			height: 40rpx;
		}
	}

	::v-deepep .u-input {
		background-color: #fff !important;
	}
</style>